package com.sd.repay.sms;

import com.sd.repay.pojo.SmsConfig;
import com.sd.repay.pojo.SmsInfo;
import com.sd.repay.utils.Md5Util;
import com.sd.repay.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
public class GKGSmsService extends BaseSmsService {

    private Logger log = LoggerFactory.getLogger(GKGSmsService.class);

    private final String channelCode = "SMS_GKG";
    private final String channelName = "";

    @Override
    public String getChannel() {

        return channelCode;
    }

    @Override
    public void smsSend(SmsInfo smsInfo, SmsConfig config) {
        log.info(channelName.concat("提交短信开始执行：{}"), smsInfo.toString());
        String sms_status = "";
        String sms_rep_code = "";
        String sms_rep_msg = "";

        String orderNo = StringUtil.stringFillLeftZero("" + smsInfo.getId(), 9);
        smsInfo.setService_id("");
        smsInfo.setReq_id(orderNo);

        try {

            String moblies = smsInfo.getMobiles();
            String channelAccount = config.getPlatform_user_name();
            String content = URLEncoder.encode(smsInfo.getSms_content(), enCode);
            String pwd = Md5Util.MD5Encode(config.getPlatform_user_name() + config.getPlatform_pwd(), enCode, true);
            String url = config.getPlatform_url();

            String sendXmlStr = getAopStr(channelAccount, pwd, moblies, content, "", orderNo);

            String soapAction = "http://entinfo.cn/mdsmssend";

            Map<String, String> header = new HashMap<String, String>();
            header.put("Accept", "application/json;charset=" + enCode);
            header.put("Content-Type", "text/xml; charset=" + enCode);
            header.put("SOAPAction", soapAction);

            HttpUtil httpUtil = new HttpUtil(timeOut, timeOut, enCode);
            String resultStr = httpUtil.httpStream(url, sendXmlStr, header, enCode);

            System.out.println("第一次请求响应：" + resultStr);
            if (StringUtil.isEmpty(resultStr)) {
                sms_status = "1";
                sms_rep_code = "Response trade result is null";
                sms_rep_msg = "提交代付渠道响应空报文";
            } else {
                String result1 = resultStr.substring(0, 1);
                if (!"-".equals(result1)) {
                    sms_status = "4";
                } else {
                    sms_status = "3";
                    sms_rep_code = resultStr;
                }
            }
        } catch (Exception e) {
            log.error(channelName.concat("手机号[{}]发送短信[{}]未知异常：{}"), smsInfo.getMobiles(), e.getMessage());
            sms_rep_code = "2";
            sms_rep_msg = "系统出现未知异常";
            e.printStackTrace();
        }
        smsInfo.setSms_rsp_code(sms_rep_code);
        smsInfo.setSms_rsp_msg(sms_rep_msg);
        smsInfo.setSms_status(sms_status);
        int count = smsDb.modifySmsStatusByReqId(smsInfo);
        log.info("手机号[{}]短信[{}]发送执行完成,通道返回状态码[{}]成功变更[{}]条记录", new Object[]{smsInfo.getMobiles(), smsInfo.getSms_content(), smsInfo.getSms_rsp_code(), count});
    }


    /**
     * 组织报文
     *
     * @param sn      软件序列号(格式XXX-XXX-XXX-XXXXX)
     * @param pwd     密码(md5(sn+password)32位大写密文)
     * @param mobile  手机号(必填(建议一次最多提交1000个))
     * @param content 内容(内容通过小逗号与手机号一一对应好URLUTF8编码)
     * @param ext     扩展码(例如：123（默认置空）)
     * @param rrid    唯一标识(最长18位)
     * @return 请求报文
     */
    private String getAopStr(String sn, String pwd, String mobile, String content, String ext, String rrid) {
        StringBuilder aop = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        aop.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        aop.append("<soap:Body>");
        aop.append("<mdsmssend  xmlns=\"http://entinfo.cn/\">");
        aop.append("<sn>").append(sn).append("</sn>");
        aop.append("<pwd>").append(pwd).append("</pwd>");
        aop.append("<mobile>").append(mobile).append("</mobile>");
        aop.append("<content>").append(content).append("</content>");
        aop.append("<ext>").append(ext).append("</ext>");
        aop.append("<stime></stime>");
        aop.append("<rrid>").append(rrid).append("</rrid>");
        aop.append("<msgfmt></msgfmt>");
        aop.append("</mdsmssend>");
        aop.append("</soap:Body>");
        aop.append("</soap:Envelope>");

        return aop.toString();
    }

}
